import React, { useState, useEffect } from 'react';
import { is_empty, cline, GridTable, useCmd, Info, WaitUmd, KInput, useKForm, obj_str, PanelTitle, ck_empty, uDb, Btn, loc } from 'sui';
import { load_col_psn } from '../psn/cmd';

const FindPsn = ({ col, hreturn, no_acc }) => {
    const [main, setMain] = useState();
    const [psn_col, psnCol] = useState();
    const [row, setRow] = useState();
    const umd = useCmd();
    const form = useKForm();

    useEffect(() => {
        load_col_psn(psnCol);
    }, []);

    const hFind = () => {
        const ck = {
            psn: v => ck_empty(v),
        };

        if (form.isErr(ck)) {
            return;
        }

        umd.startWait();

        uDb(null, "psn/get",
            {
                line: cline(),
                k: form.get("psn"),
            },
            r => {
                setMain(r);

                uDb(umd.endWait, "task/get",
                    {
                        line: cline(),
                        k: obj_str(r, "task"),
                    },
                    pr => setRow([pr]),
                    pe => setRow(null));
            },
            e => {
                setMain(null);
                umd.setErr(loc("l_196"));
            });
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [];

        col.forEach(d => {
            if (d.key === "index" || d.key === "e_opt") {
                return;
            }

            tmp.push(d);
        });

        return tmp;
    };

    return (
        <div>
            <PanelTitle cl="gray">
                <div className="inline-flex mb-2">
                    <Btn hcmd={() => hFind()} color="green" className="mr-4">{loc("l_551")}</Btn>
                    <KInput label={loc("l_152")} form={form} name="psn" mg="dense" width="w-64"/>
                </div>
            </PanelTitle>
            <GridTable high={100} col={getCol()} row={row} rowHeight={45}/>
            <Info col={psn_col} data={main} className="ml-4 text-xl mt-2"/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {FindPsn};
